package com.shengqi.xinnongren.work.ui.home.presenter;

import com.google.gson.Gson;
import com.shengqi.xinnongren.common.base.BasePresenter;
import com.shengqi.xinnongren.common.config.network.Constants;
import com.shengqi.xinnongren.common.config.network.RetrofitHelper;
import com.shengqi.xinnongren.common.config.user.UserManager;
import com.shengqi.xinnongren.work.model.HttpRespond;
import com.shengqi.xinnongren.work.ui.Global;
import com.shengqi.xinnongren.work.ui.home.model.SearchBean;
import com.shengqi.xinnongren.work.ui.home.view.SearchView;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class SearchPresenter extends BasePresenter<SearchView> {
    public void getHotSearch() {
        JSONObject jsonData = Constants.getJsonData(null, UserManager.getInstance().getToken());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonData.toString());
        addTask(RetrofitHelper.getInstance().getService().getHotSearchList(requestBody), hotSearchBeanHttpRespond -> {
            if (hotSearchBeanHttpRespond.result == 1) {
                getView().showHotSearchList(hotSearchBeanHttpRespond.data);
            } else
                getView().onRequestFailed(hotSearchBeanHttpRespond.message);

        });
    }

    public void getSearchList(String content) {
        getView().showLoadingView();
        Map<String, Object> map = new HashMap<>();
        map.put("searchKeyWord", content);
        JSONObject jsonData = Constants.getJsonData(map,  UserManager.getInstance().getToken());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonData.toString());
        addTask(RetrofitHelper.getInstance().getService()
                .getSearchList(requestBody), searchBeanHttpRespond -> {
            getView().hideLoadingView();
            HttpRespond<String> httpResult = Global.getHttpResult(searchBeanHttpRespond);
            if (httpResult.result == 1) {
                SearchBean bean = new Gson().fromJson(httpResult.data, SearchBean.class);
                getView().showSearchList(bean);
            } else
                getView().onRequestFailed(httpResult.message);
        });
    }

    public void getShoppingCartNum() {
        JSONObject jsonData = Constants.getJsonData(null, UserManager.getInstance().getToken());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonData.toString());
        addTask(RetrofitHelper.getInstance().getService().getShoppingCartNum(requestBody), s -> {
            HttpRespond<String> httpResult = Global.getHttpResult(s);
            if (httpResult.result == 1) {
                int num = Integer.parseInt(httpResult.data);
                getView().onGetShoppingCartNum(num);
            }
        });
    }
}
